package com.aiden.app.common.extension

import java.math.BigDecimal
import java.text.DecimalFormat
import java.util.regex.Pattern

/**
 * Descriptions：
 * <p>
 * Author：ChenME
 * Date：2019/4/17
 * Email：ibelieve1210@163.com
 */

fun String.formatRichText(): String {
    return """
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body {
            font-size: 16px;
        }
    </style>
</head>
<body>
    <script type='text/javascript'>
        window.onload = function () {
            var img = document.getElementsByTagName('img');
            for (var p in img) {
                img[p].style.width = '100%';
                img[p].style.height = 'auto'
            }
        }
    </script>
    $this
</body>
</html>
            """.trimIndent().replace("style=\"white-space: nowrap;\"", "")
}

fun String.formatRichTextWithTitle(title: String): String {
    return """
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body {
            font-size: 16px;
        }
    </style>
</head>
<body>
    <script type='text/javascript'>
        window.onload = function () {
            var img = document.getElementsByTagName('img');
            for (var p in img) {
                img[p].style.width = '100%';
                img[p].style.height = 'auto'
            }
        }
    </script>
    <h3>$title</h3>
    $this
</body>
</html>
            """.trimIndent().replace("style=\"white-space: nowrap;\"", "")
}

fun String?.isNilWithoutNull(): Boolean {
    return null == this || this.trim().isEmpty()
}

fun String?.isNil(): Boolean {
    return null == this || this.trim().isEmpty() || this == "null"
}

fun CharSequence?.isNil(): Boolean {
    return null == this || this.length == 0 || this == "null"
}

fun String?.isNotNil(): Boolean {
    return !isNil()
}

fun String?.notNullText(): String {
    return if (null == this || this == "null") "" else this
}

fun CharSequence?.isNotNil(): Boolean {
    return !isNil()
}

fun CharSequence?.notNullText(): String {
    return if (null == this || this == "null") "" else this.toString()
}

/**
 * 最长 N 个字，之后省略
 */
fun String?.maxLetter(maxLength: Int = 6): String {
    if (null == this || isEmpty()) {
        return ""
    }
    if (this.length <= maxLength) {
        return this
    }
    return "${this.substring(0 until maxLength)}..."
}

fun String?.convertStarScore(): String {
    if (isNil()) {
        return "0.0"
    }
    var tmp = BigDecimal(0)
    try {
        tmp = this!!.toBigDecimal()
    } catch (e: Exception) {

    }
    return DecimalFormat("0.0").format(tmp)
}

fun String?.convertStarScorePercent(): String {
    if (isNil()) {
        return "100%"
    }
    var tmp = 5.0f
    var result = 100
    try {
        tmp = this!!.toFloat()
        result = ((tmp / 5) * 100f).toInt()
    } catch (e: Exception) {

    }
    return "$result%"
}

fun String?.convertMoney(): String {
    if (isNil()) {
        return "0.00"
    }
    var tmp = BigDecimal(0)
    try {
        tmp = this!!.toBigDecimal()
    } catch (e: Exception) {

    }
    return DecimalFormat("0.00").format(tmp)
}

/**
 * 将金钱转换成整数部分和小数部分
 */
fun String?.convertMoney2IntAndPoint(): List<String> {
    if (isNil()) {
        return arrayListOf("", "")
    }
    if (this!!.contains(".")) {
        return this.split(".")
    }
    return arrayListOf(this, "00")
}

fun String?.toRemark(): String {
    return if (isNil()) "无备注" else this!!
}

fun String?.toRefuseReason(): String {
    return if (isNil()) "未填写拒绝原因" else this!!
}

fun String?.convertEvaluateContent(): String {
    return if (isNil()) "此用户没有填写评价" else this!!
}


fun String?.notNilNumber(): String {
    return if (isNil()) "0" else this!!
}

fun CharSequence.isIdCard(): Boolean {
    val regIdCard = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}\$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X|x)\$"
    return Pattern.compile(regIdCard).matcher(this).matches()
}

fun CharSequence.isPhone(): Boolean {
    val regPhone = "^1[0-9]{10}\$"
    return Pattern.compile(regPhone).matcher(this).matches()
}

fun String?.secretCardNum(): String {
    if (this.isNil()) {
        return ""
    }
    if (this!!.length < 4) {
        return this
    }
    return "**** **** **** ${this.substring(this.length - 4 until this.length)}"
}

/**
 * 将电话号码加密
 */
fun String?.secretPhone(replaceString: String = "****"): String {
    if (this.isNil()) {
        return ""
    }
    if (this!!.length < 4) {
        return this
    }
    return this.substring(0..2) + replaceString + this.substring(this.length - 4 until this.length)
}

fun String?.secretUserName(replaceString: String = "***"): String {
    if (this.isNil()) {
        return replaceString
    }
    if (this!!.length <= 2) {
        return this.substring(0..0) + replaceString
    }
    return this.substring(0..0) + replaceString + this.substring(this.length - 1 until this.length)
}

/**
 * 格式化需求服务类型，按逗号（,）分割，给每一项添加#号
 */
fun String?.formatServiceType(key: String = ","): String {
    if (isNil()) {
        return ""
    }
    val serviceTypes = this?.split(key)
    val result = StringBuilder()
    if (serviceTypes.isNotNil()) {
        serviceTypes?.forEach {
            if (it.isNotNil()) {
                result.append("#$it ")
            }
        }
    }
    return result.toString()
}

fun CharSequence?.isNotNilTime(): Boolean {
    return !isNil() && this != "0"
}

fun String?.notNullValue(): String {
    return if (isNil()) "" else this!!
}

/**
 * 将字符串转换成整型，如果异常则返回默认值
 */
fun String?.toIntNoException(defaultInt: Int = -1): Int {
    if (null == this) {
        return defaultInt
    }
    return try {
        this.toInt()
    } catch (e: Exception) {
        e.printStackTrace()
        defaultInt
    }
}

fun String?.isNotNilNumber(): Boolean {
    return !isNil() && this?.toDouble()!! > 0
}
